import { createRouter, createWebHashHistory } from 'vue-router';

import Login from '../components/Login.vue';
import Home from '../components/Home.vue';

import Welcome from '../view/Welcome.vue';
import Users from '../view/user/Users.vue';
import Rights from '../view/power/Rights.vue';
import Roles from '../view/power/Roles.vue';

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login, meta: { title: '登录页面' } },
  {
    path: '/home',
    component: Home,
    meta: { title: '主页' },
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome, meta: { title: '欢迎您' } },
      { path: '/users', component: Users, meta: { title: '用户列表' } },
      { path: '/rights', component: Rights, meta: { title: '权限列表' } },
      { path: '/roles', component: Roles, meta: { title: '角色列表' } },
      //
      { path: '/goods', component: Welcome, meta: { title: '欢迎您' } },
      { path: '/params', component: Welcome, meta: { title: '欢迎您' } },
      { path: '/categories', component: Welcome, meta: { title: '欢迎您' } },
      { path: '/orders', component: Welcome, meta: { title: '欢迎您' } },
      { path: '/reports', component: Welcome, meta: { title: '欢迎您' } },
    ],
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  document.title = `${to.meta.title} | 电商管理系统`;
  if (to.path === '/login') return next();
  const tokenStr = window.sessionStorage.getItem('token');

  if (!tokenStr) return next('/login');
  next();
});

export default router;
